package com.intelligent.security;

import com.intelligent.service.UserService;
import com.intelligent.utils.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class AuthorizationAspect {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    @Before("@annotation(com.intelligent.security.RequiresPermission) || @within(com.intelligent.security.RequiresPermission)")
    public void checkPermission(JoinPoint joinPoint) {
        String required = resolveRequiredPermission(joinPoint);
        if (required == null || required.isEmpty()) {
            return; // no specific permission required
        }
        Object uidObj = request.getAttribute("CURRENT_USER_ID");
        if (uidObj == null) {
            throw new RuntimeException("未认证用户");
        }
        Long userId = Long.parseLong(String.valueOf(uidObj));
        List<String> permissions = userService.getPermissionsByUserId(userId);
        if (permissions == null || !permissions.contains(required)) {
            throw new RuntimeException("无权限: " + required);
        }
    }

    private String resolveRequiredPermission(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RequiresPermission ann = method.getAnnotation(RequiresPermission.class);
        if (ann != null)
            return ann.value();
        Class<?> targetClass = joinPoint.getTarget().getClass();
        RequiresPermission classAnn = targetClass.getAnnotation(RequiresPermission.class);
        return classAnn != null ? classAnn.value() : null;
    }
}
